#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"

APP_INSTALL_NAME="dreamcube"
APP_TARGET_DIR_NAME="dreamcube"

export CURRENT_APP_PATH="$LMD_APPS_DIR/$APP_TARGET_DIR_NAME"
echo "App Dir: ${CURRENT_APP_PATH}"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

cd "$CURRENT_APP_PATH"
conda --version

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export GRADIO_TEMP_DIR="$CURRENT_APP_PATH/temp_gradio"
CONDA_PREFIX="./venv"


export HF_HOME="./tmp_hf_home"
export U2NET_HOME="./unet_home"
export TORCH_HOME="./tmp_torch_home"

if current_os_is_windows; then
    APP_SCRIPT_DIR="$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME"
    UTILS_OPS_DIR="$CURRENT_APP_PATH/utils/ops"
    cp -f "$APP_SCRIPT_DIR/cp312/torch2.7.0/cu128/resample_padding_plugin.pyd" "$UTILS_OPS_DIR"

    if [ -e "$UTILS_OPS_DIR/resample_padding_bak.py" ]; then
        echo "resample_padding_bak.py exists"
    else
        cp "$UTILS_OPS_DIR/resample_padding.py" "$UTILS_OPS_DIR/resample_padding_bak.py"
        echo "backup resample_padding_bak.py"
    fi
    cp -f "$APP_SCRIPT_DIR/resample_padding.py" "$UTILS_OPS_DIR"
fi

cd "$CURRENT_APP_PATH"

sed 's/demo\.launch(.*)/demo.launch()/g' app.py > app_temp.py

conda run -p "$CONDA_PREFIX" --no-capture-output python app_temp.py --use-gradio
